<script setup lang="ts">
import { getHomeBannerAPI, getHomeCategoryAPI, getHomeHotMutliAPI } from '@/services/home'
import { onMounted, ref } from 'vue'
import type { BannerItem, CategoryItem, HotItem } from '@/types/home'
//import type { XtxGuessInstance } from '@/types/component'
import CustomNavbar from './components/CustomNavbar.vue'
import CategoryPanel from './components/CategoryPanel.vue'
import HotPanel from './components/HotPanel.vue'
import PageSkeleton from './components/PageSkeleton.vue'
import { useGuessList } from '@/composables'

// 获取轮播图数据
const bannerList = ref<BannerItem[]>([])
const getHomeBannerData = async () => {
  const res = await getHomeBannerAPI()
  //console.log(res)
  bannerList.value = res.result
}

// 获取前台分类数据
const categoryList = ref<CategoryItem[]>([])
const getHomeCategoryData = async () => {
  const res = await getHomeCategoryAPI()
  //console.log(res)
  categoryList.value = res.result
}

// 获取热门推荐数据
const hotMutlList = ref<HotItem[]>([])
const getHomeHotMutlData = async () => {
  const res = await getHomeHotMutliAPI()
  //console.log(res)
  hotMutlList.value = res.result
}

// 滚动触底出发事件
/* const guessRef = ref<XtxGuessInstance>() // 获取组件实例
const onScrolltolower = () => {
  guessRef.value?.getMore()
} */
const { guessRef, onScrolltolower } = useGuessList()

const isTriggered = ref(false)
// 自定义下拉刷新
const onRefresherrefresh = async () => {
  isTriggered.value = true
  /* await getHomeBannerData()
  await getHomeCategoryData()
  await getHomeHotMutlData() */
  guessRef.value?.resetData()
  await Promise.all([
    getHomeBannerData(),
    getHomeCategoryData(),
    getHomeHotMutlData(),
    guessRef.value?.getMore(),
  ])
  isTriggered.value = false
}
const isLoading = ref(false)

// 页面加载
onMounted(async () => {
  isLoading.value = true
  /* getHomeBannerData()
  getHomeCategoryData()
  getHomeHotMutlData() */
  await Promise.all([getHomeBannerData(), getHomeCategoryData(), getHomeHotMutlData()])
  isLoading.value = false
})
</script>

<template>
  <!-- 自定义导航栏 -->
  <CustomNavbar />
  <!-- 滚动 -->
  <scroll-view
    @scrolltolower="onScrolltolower"
    refresher-enabled
    @refresherrefresh="onRefresherrefresh"
    :refresher-triggered="isTriggered"
    scroll-y
    class="scroll-view"
  >
    <!-- 骨架 -->
    <PageSkeleton v-if="isLoading"></PageSkeleton>
    <template v-else>
      <!-- 轮播图 -->
      <XtxSwiper :list="bannerList"></XtxSwiper>
      <!-- 分类 -->
      <CategoryPanel :list="categoryList"></CategoryPanel>
      <!-- 热门推荐 -->
      <HotPanel :list="hotMutlList"></HotPanel>
      <!-- 猜你喜欢 -->
      <XtxGuess ref="guessRef"></XtxGuess>
    </template>
  </scroll-view>
</template>

<style lang="scss">
page {
  background-color: #f7f7f7;
  height: 100%;
  display: flex;
  flex-direction: column;
  .scroll-view {
    flex: 1;
  }
}
</style>
